﻿// /////////////////////////////////// 
//  
//  
//      WiseLink CCF2.0 
//     (c)Copyright 2001-2010 WiseLink Xiaojun (David) Chen 
//        Authored and Owned Xiaojun (David) Chen 
//        All Right Reserved
//  
// /////////////////////////////////// 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;
using CCF20Model;
using WiseLink.RDS.Resource;


namespace CCF20Model
{
    public class eRDSZIC : ZICBase
    {
        public eRDSZIC()
        {
            LoggerHelper.LogCCF20(string.Format("e ZIC Url: {0}", zicUrl));
        }

        public static bool DeviceRegister(Device device, string IDSName, string idsid,string SN, string SNKey)
        {

            object[] parameters = new object[] { 
                                            SN,
                                            idsid,
                                            SNKey,
                                            device.Vehicle.VehicleLicense,
                                            device.Customer.Name,
                                            "32",
                                            device.Vehicle.VehicleType.Model,
                                            device.Customer.IdentityNo,
                                            "CCF",
                                            device.Vehicle.ChassiNo,
                                            device.Vehicle.EngineNo,
                                            device.Vehicle.VehicleType.Displacement,
                                            device.Vehicle.VehicleType.EngineType
                                          };
            DateTime registerDate;

            string ret = ExectueMethod(ZICMethod.ProductRegister, parameters);
            

            RegisterModel registerModel = null;
            try
            {
                registerModel = jsonSerializer.Deserialize<RegisterModel>(ret);
                LoggerHelper.LogCCF20("eZIC  Device Register Succeed");
                
                //"IDCRegisterDate=2011-05-12 04:32:36"
                if (DateTime.TryParse(registerModel.IDCRegisterDate, out registerDate))
                {
                    LoggerHelper.LogCCF20(string.Format("Successfully parse the RegisterDate from ZIC {0}", registerDate));
                }
                else
                {
                    registerDate = DateTime.Now;
                    LoggerHelper.LogCCF20(string.Format("Failed to parse the RegisterDate from ZIC {0}", registerModel.IDCRegisterDate));
                }
                device.RegisterDate = registerDate;
                device.DeviceKey = registerModel.key;
                device.IDCSimNumber = registerModel.idc;
                device.DeviceType = registerModel.DeviceType;
                device.Customer.IDSID = Convert.ToInt16(idsid);
                device.Customer.IDS = IDSName;
                device.IsRegistered = true;
                device.DeviceStatus = WiseLinkRDSStatus.Device_Sold;
                device.Customer.SN = SN;
                device.Customer.SNPwd = SNKey;
                device.Vehicle.LastContactResult = WiseLinkRDSStatus.Contact_NotContactYet;
                device.Vehicle.PreviousContactResult = string.Empty;
                device.IsTrial = registerModel.applyType ==null? false: (registerModel.applyType.Contains("试用") ? true : false);
                return true;
            }
            catch (Exception ex)
            {
                LoggerHelper.LogCCF20(string.Format("NET Device Register Error: {0}", ret));
                throw ex;
            }
            
        }
        public static void GetWiseLinkIDS()
        {
            CCF20Entities ccf20Ent = new CCF20Entities();
            int maxId = ccf20Ent.WiseLinkIDS.Max(w => w.IDS).GetValueOrDefault();
            
            object[] parameters;
            if (ZICBase.svcType == ZICType.eRDS)
            {
                parameters = new object[] { "", "", maxId };
            }
            else
            {
                parameters = new object[] { "", ""};
            }

            string ret = ExectueMethod(ZICMethod.GetShopInfoByIds, parameters);
            
            if (ret == null) return;
            
            List<CustomerInfo> list = jsonSerializer.Deserialize<List<CustomerInfo>>(ret);
            
            foreach (CustomerInfo customerInfo in list)
            {
                WiseLinkIDS ids = new WiseLinkIDS();
                ids.IDS = Convert.ToInt32(customerInfo.ids);
                ids.CompanyName = customerInfo.CompanyName;
                ids.CompanyAddress = customerInfo.CompanyAddress;
                ids.OwnerName = customerInfo.ExcuteMan;
                ids.Mobile = customerInfo.CompanyPhone;
                ids.CustomerType = customerInfo.cusType;
                ids.IDSType = customerInfo.idstype;
                ccf20Ent.WiseLinkIDS.AddObject(ids);
            }
            ccf20Ent.SaveChanges();

        }

        public static bool GetDeviceKey(Device device, string SN, string SNKey)
        {

            object[] parameters = new object[] {SN, SNKey };
            

            string ret = ExectueMethod(ZICMethod.GetKey, parameters);


            RegisterModel registerModel = null;
            try
            {
                registerModel = jsonSerializer.Deserialize<RegisterModel>(ret);
                LoggerHelper.LogCCF20("eZIC  Device GetKey Succeed");

                device.DeviceKey = registerModel.key;
                device.IDCSimNumber = registerModel.idc;
                device.DeviceType = registerModel.DeviceType;
                return true;
            }
            catch (Exception ex)
            {
                LoggerHelper.LogCCF20(string.Format("NET Device GetKey Error: {0} Exception: {1}", ret, ex.Message));
                return ValideReturnMessageFromZIC(ret);
            }

        }

        public static void GetVehicleType()
        {
            int temp = maintenanceModel.GetMaxVehicleTypeID();
            string ret;
            LoggerHelper.LogCCF20(string.Format("获取ZIC车型：LastAnchiID={0}", temp));
            ret = ExectueMethod(ZICMethod.GetCarTy, new object[]{temp.ToString()});
            
            if (ret == null) return;
            List<CarTyModel> list = jsonSerializer.Deserialize<List<CarTyModel>>(ret);

            foreach (CarTyModel model in list)
            {
                //if ((ZICMonitorModel.IsJava && model.brand.Trim() != "FAW-VW") ||
                //    (!ZICMonitorModel.IsJava && model.brand.Trim() == "FAW-VW"))
                //{

                if (model.id != null && model.id > 0)
                {

                    VehicleType vehicleType = new VehicleType();
                    vehicleType.AnchiID = model.id;
                    vehicleType.Model = model.carType.Trim();
                    vehicleType.Manufacture = model.brand.Trim();
                    vehicleType.EngineType = model.Engine_type.Trim();
                    vehicleType.Displacement = model.displacement.Trim();
                    vehicleType.ModelYear = model.CAR_YEAR;
                    maintenanceModel.UpdateVehicleType(vehicleType);
                }
                else
                {
                    LoggerHelper.LogCCF20(string.Format("[ Warning GetVehicleType] AnchiID 为空 厂商={0} 车型={1} 引擎={2}", model.brand, model.carType, model.Engine_type));
                }

            }
            maintenanceModel.Update();
        }
        //在从ZIC 获取的车型和保养项目中，AnchiID 都是从ZIM的车型表和保养表中的记录ID。
        //保养项目中的TYID 对应于车型表中的 ZIM ID （ANCHIID)
        //保养项目中的VehicleTypeID 对应于车型表中的 实际的记录 ID （ANCHIID)
        public static void GetMaintenanceType()
        {
            int temp = maintenanceModel.GetMaxMaintenanceTypeID();
            string ret;
            LoggerHelper.LogCCF20(string.Format("获取ZIC保养项目：IDS={0} Pwd={1},LastAnchiID={2}", PID, Pwd, temp));
            ret = ExectueMethod(ZICMethod.GetTymaintain, new object[] { temp.ToString() });
            if (ret == null) return;
            List<TymaintainModel> list = jsonSerializer.Deserialize<List<TymaintainModel>>(ret); 

            foreach (TymaintainModel model in list)
            {

                int tempVehicleType = 0;
                int.TryParse(model.tyid, out tempVehicleType);
                if (model.id > 0 && tempVehicleType > 0)
                {
                    LoggerHelper.LogCCF20(string.Format("TyID:{0}\tAnchiID:{1}\tName:{2}", model.tyid, model.id, model.MaintainPj.Trim()));
                    MaintenanceType maintenanceType = new MaintenanceType();
                    maintenanceType.VehicleTypeID = tempVehicleType;
                    maintenanceType.TyID = model.tyid;
                    maintenanceType.AnchiID = model.id;
                    maintenanceType.ServicePeriod = (model.MaintainPeriod == null ? 0 : Convert.ToInt32(model.MaintainPeriod));
                    maintenanceType.Name = model.MaintainPj.Trim();
                    maintenanceType.ServiceMileage = (model.mileage == null ? 0 : Convert.ToInt32(model.mileage));
                    maintenanceType.Priority = 1;
                    maintenanceModel.UpdateMaintenanceType(maintenanceType);
                    maintenanceModel.Update();
                }
                else
                {
                    LoggerHelper.LogCCF20(string.Format("[Waring GetMaintenanceType]TyID=0 or Model.Id=0 Name:{0}", model.MaintainPj));
                }
            }

        }
        public static void GetClearCodeResult()
        {
            string ret;

            
                LoggerHelper.LogCCF20(string.Format("GetClearCodeResult: PID={0},Pwd={1},AnChiID={2}",
                                                        PID,
                                                        Pwd,
                                                        vehicleModel.GetMaxClearCodeResultId()));
                ret = ExectueMethod(ZICMethod.GetClearcoderesult, new object[] { PID, Pwd, vehicleModel.GetMaxClearCodeResultId() });
                
                if (ret == null) return;
                List<ClearcodeResultData> list = jsonSerializer.Deserialize<List<ClearcodeResultData>>(ret); 
                foreach (ClearcodeResultData clearCodeResult in list)
                {
                    ClearCodeHistory clearCodeHistory = new ClearCodeHistory();
                    int tempId;
                    clearCodeHistory.AnchiID = int.TryParse(clearCodeResult.id, out tempId) ? tempId : 0;
                    clearCodeHistory.ErrMsg = clearCodeResult.errMessage;
                    clearCodeHistory.IDCSimNumber = clearCodeResult.idc.Trim();
                    switch (clearCodeResult.sendStatu.Trim())
                    {
                        case "0":
                            clearCodeHistory.SendStatus = "未发送";
                            break;
                        case "1":
                            clearCodeHistory.SendStatus = "发送成功";
                            break;
                        case "2":
                            clearCodeHistory.SendStatus = "发送失败";
                            break;
                        case "9":
                            clearCodeHistory.SendStatus = "准备发送";
                            break;
                        case "90":
                            clearCodeHistory.SendStatus = "等待返馈";
                            break;
                        default:
                            clearCodeHistory.SendStatus = string.Format("未知代码:{0}", clearCodeResult.sendStatu);
                            break;
                    }

                    DateTime tempDate;
                    clearCodeHistory.SendTime = DateTime.TryParse(clearCodeResult.sendTime, out tempDate) ? tempDate : DateTime.Now;
                    vehicleModel.AddClearCodeResult(clearCodeHistory);
                }


            
        }

        public static string ClearCode(string idc, string codeType)
        {
            return ExectueMethod(ZICMethod.ClearCodes, new object[] { PID, Pwd, idc, 14,codeType });
            
        }

    }
}
